package de.koller.worlders.engine.util.thread;

public class ValueThread {
	
	private final AsyncE asyncThread;
	private final IVThread readyHandler;
	private boolean calculated = false;

	private ValueThread( IVThread asyncHandler, IVThread readyHandler ) {
		this.asyncThread = new AsyncE( asyncHandler );
		this.readyHandler = readyHandler;
	}
	
	public static ValueThread create( IVThread asyncHandler, IVThread readyHandler ) {
		return new ValueThread( asyncHandler, readyHandler );
	}
	
	public void startCalculateAsync() {
		if( !asyncThread.ready )
			return;
		
		if( asyncThread.running == false )
			asyncThread.start();
		
		calculated = false;
		synchronized( asyncThread ) {
			asyncThread.ready = false;
			asyncThread.notifyAll();
		}
	}
	
	public boolean calculateReadyWhenReady() {
		if( !asyncThread.ready  )
			return false;
		
		if( calculated )
			return false;
		
		readyHandler.handleThread();
		calculated = true;
		return true;
	}
	
	public void stop() {
		asyncThread.running = false;
	}
	
	private static class AsyncE extends Thread {
		private final IVThread async;
		private boolean running = false;
		private boolean ready = true;

		private AsyncE( IVThread async ) {
			this.async = async;
			this.setDaemon( true );
		}

		@Override
		public synchronized void start() {
			super.start();
			
			running = true;
		}

		@Override
		public void run() {
			while( running ) {
				synchronized( this ) {
					try {
						while( ready ) { this.wait(); }
					} catch( InterruptedException ex ) {}
				}	
				
				async.handleThread();		
				ready = true;
			}
		}
		
	}
}
